import { nextTick, onMounted, ref } from "vue";
import { getMessage } from "@/api/zixun";
import useChat from "./useChat";
import type { ChatItemProps } from "@/components/Chat/chat.vue";
import { interpreter } from "@/api/request";
import debounce from "@/utils/debounce";
import { onLoad } from "@dcloudio/uni-app";
import { AIToken, Token } from "@/utils/cache";
import { useTabs } from "@/store/tab";

export default function useIndex() {
  const { getTabById } = useTabs();

  const tabItem = ref<any>();
  const ignoreChance = ref();
  const {
    source,
    chats,
    chating,
    getActiveRobot,
    onGetAudio,
    getConversationHistory
  } = useChat();

  const conversationChat = ref<{
    robot: ChatItemProps;
    user: ChatItemProps;
  } | null>(null);

  const historyPopup = ref();
  const hotMessage = ref<string>("");

  const onSendMessage = debounce(async (value: string) => {
    if (conversationChat.value) {
      uni.showToast({
        title: "正在回复中...",
        icon: "none"
      });
      return;
    }
    if (tabItem.value?.id) {
      hotMessage.value = "";
      conversationChat.value = {
        robot: { msg: "" },
        user: { question: value }
      };
      const [err] = await interpreter(getMessage(value, tabItem.value.id), {
        showLoading: false,
        ignores: []
      });
      if (err) {
        console.log("err", err);
        if (err.error_code === 403) {
          conversationChat.value = null;
          ignoreChance.value.open();
        } else {
          uni.showToast({
            duration: 3000,
            title: "发送失败，" + err.result.msg,
            icon: "none"
          });
        }
        conversationChat.value = null;
      }
    }
  });

  const onSetHotMessage = (content: string) => {
    hotMessage.value = content;
  };

  const onClear = () => {
    chats.value = [];
  };
  onLoad(async (options: any) => {
    if (options) {
      const item = await getTabById(+options.id);
      if (item) {
        await nextTick();
        // #ifdef H5
        document.title = item.nickname;
        // #endif
      }
      tabItem.value = item;
      if (Token.get() && AIToken.get()) {
        getConversationHistory(tabItem.value.id);
      }
    }
  });
  return {
    ignoreChance,
    tabItem,
    historyPopup,
    getActiveRobot,
    source,
    chats,
    chating,
    conversationChat,
    // tabs,
    hotMessage,
    onClear,
    getConversationHistory,
    onSendMessage,
    onGetAudio,
    onSetHotMessage
  };
}
